<?php

namespace Beerus\Modules\BrandFlowPool\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\cache\brand\FlowPoolWhite as cFlowPoolWhite;
use Biz\model\brandFlowPool\FlowPoolWhite as mFlowPoolWhite;
use Biz\model\brand\Brand;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class IndexController extends Controller
{
    public function index(Request $request, Content $content)
    {
        $brandId = $request->input('brand_id', 0);
        if ($brandId) {
            $condition['brand_id'] = $brandId;
        }
        $pageSize = $request->input("per_page", 20);
        $page = $request->input("page", 1);
        $condition['LIMIT'] = [
            ($page - 1) * $pageSize,
            $pageSize
        ];
        $list = mFlowPoolWhite::selectByWhere(['ORDER' => ['id' => 'DESC'], 'start_time[>]' => 0, 'end_time[>]' => 0], '*');
        $brandIds = array_column($list, 'brand_id');
        $brandInfos = $brandIds ? Brand::getInfoByIds($brandIds) : [];
        $brandInfos = $brandInfos ? array_column($brandInfos, null, 'id') : [];
        foreach ($list as &$row) {
            $row['brand_name'] = isset($brandInfos[$row['brand_id']]) ? $brandInfos[$row['brand_id']]['brand_name'] : '';
        }
        $total = mFlowPoolWhite::selectCountWhere([]);
        $gridModel = new pGridDataModel($list, $total, ['perPage' => $pageSize]);
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->filter(function ($filter) {
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('brand_id', '品牌id');
                    });
                    $filter->disableIdFilter();
                    $filter->expand();//默认展开
                });
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->column('id', 'id');
                $grid->column('brand_id', '品牌id');
                $grid->column('brand_name', '品牌名称');
                $grid->column('start_time', '开始时间')->display(function () {
                    return date('Y-m-d', $this->start_time);
                });
                $grid->column('end_time', '结束时间')->display(function () {
                    return date('Y-m-d', $this->end_time);
                });

                $grid->actions(function (Grid\Displayers\Actions $actions) {
//                    $actions->disableEdit();
//                    $actions->disableDelete();
                });
            }
        );

        return $content
            ->header('品牌流量池白名单列表')
            ->description(' ')
            ->row($gridList->render());
    }

    public function edit(Request $request, Content $content, $id = 0)
    {
        $info = $id ? mFlowPoolWhite::getByWhere(['id' => $id]) : [];
        $info['start_time'] = ($info && $info['start_time']) ? date('Y-m-d', $info['start_time']) : '';
        $info['end_time'] = ($info && $info['end_time']) ? date('Y-m-d', $info['end_time']) : '';
        $form = new Form($info);
        $form->hidden('id', 'id');
        $form->text('brand_id', '品牌id')->required()->width('110px');
        $form->date('start_time', '开始时间')->required();
        $form->date('end_time', '结束时间')->required();
        $form->action('/admin/brandFlowPool/save');
        return $content
            ->header('编辑品牌流量池白名单')
            ->description(' ')
            ->breadcrumb(
                ['text' => '编辑品牌流量池白名单']
            )
            ->row($form);
    }

    public function save(Request $request)
    {
        try {
            $id = $request->input('id', 0);
            $brandId = $request->input('brand_id', 0);
            $startTime = $request->input('start_time', '');
            $endTime = $request->input('end_time', '');
            if (empty($brandId) || empty($startTime) || empty($endTime) || $startTime > $endTime) {
                throw new \Exception('参数错误');
            }
            $startTime = strtotime($startTime);
            $endTime = strtotime($endTime) + 86399;
            if ($id) {
                mFlowPoolWhite::updateData(['brand_id' => $brandId, 'start_time' => $startTime, 'end_time' => $endTime], ['id' => $id]);
            } else {
                mFlowPoolWhite::insertData(['brand_id' => $brandId, 'start_time' => $startTime, 'end_time' => $endTime]);
            }
            $this->changeBrandCache($brandId);
            return redirect('/admin/brandFlowPool/index')->with(compact('success'));
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '保存失败,' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }

    public function del(Request $request, $id)
    {
        $info = mFlowPoolWhite::getByWhere(['id' => $id]);
        $brandId = $info['brand_id'];
        $result = mFlowPoolWhite::updateData(['start_time' => 0, 'end_time' => 0], ['id' => $id]);
        if ($result) {
            $status = true;
            $message = "删除成功";
        } else {
            $status = false;
            $message = "删除失败";
        }
        $this->changeBrandCache($brandId);
        return response()->json(compact('status', 'message'));
    }

    public function changeBrandCache($brandId)
    {
        cFlowPoolWhite::delBrand($brandId);
        $time = time();
        $count = mFlowPoolWhite::selectCountWhere(['start_time[<=]' => $time, 'end_time[>=]' => $time, 'brand_id' => $brandId]);
        if ($count) {
            cFlowPoolWhite::addBrand([$brandId]);
        }
    }

}